package main

import (
	"github.com/veandco/go-sdl2/sdl"
)

type Game struct {
	Player1 *PlayerSprite
	Player2 *PlayerSprite
}

func NewGame(t *Texture) *Game {
	g := &Game{
		Player1: NewPlayer1Sprite(t),
		Player2: NewPlayer2Sprite(t),
	}
	return g
}

func (this *Game) Render() {
	this.Player1.Render()
	this.Player2.Render()
}

func (this *Game) Event() {
	this.Player1Event()
	this.Player2Event()
}

func (this *Game) Player1Event() {
	keyState := sdl.GetKeyboardState()
	x, y := this.Player1.GetXY()
	d := this.Player1.GetDirect()
	if keyState[sdl.SCANCODE_W] > 0 {
		if !CheckCollision(this.Player1.GetRect(), this.Player2.GetRect(), sdl.Rect{Y: -2}) {
			y -= 2
		}
		d = 0
	} else if keyState[sdl.SCANCODE_A] > 0 {
		if !CheckCollision(this.Player1.GetRect(), this.Player2.GetRect(), sdl.Rect{X: -2}) {
			x -= 2
		}
		d = 3
	} else if keyState[sdl.SCANCODE_S] > 0 {
		if !CheckCollision(this.Player1.GetRect(), this.Player2.GetRect(), sdl.Rect{Y: 2}) {
			y += 2
		}
		d = 2
	} else if keyState[sdl.SCANCODE_D] > 0 {
		if !CheckCollision(this.Player1.GetRect(), this.Player2.GetRect(), sdl.Rect{X: 2}) {
			x += 2
		}
		d = 1
	}
	this.Player1.SetDirect(d)
	this.Player1.SetXY(x, y)
}

func (this *Game) Player2Event() {
	keyState := sdl.GetKeyboardState()
	x, y := this.Player2.GetXY()
	d := this.Player2.GetDirect()
	if keyState[sdl.SCANCODE_UP] > 0 {
		if !CheckCollision(this.Player2.GetRect(), this.Player1.GetRect(), sdl.Rect{Y: -2}) {
			y -= 2
		}
		d = 0
	} else if keyState[sdl.SCANCODE_LEFT] > 0 {
		if !CheckCollision(this.Player2.GetRect(), this.Player1.GetRect(), sdl.Rect{X: -2}) {
			x -= 2
		}
		d = 3
	} else if keyState[sdl.SCANCODE_DOWN] > 0 {
		if !CheckCollision(this.Player2.GetRect(), this.Player1.GetRect(), sdl.Rect{Y: 2}) {
			y += 2
		}
		d = 2
	} else if keyState[sdl.SCANCODE_RIGHT] > 0 {
		if !CheckCollision(this.Player2.GetRect(), this.Player1.GetRect(), sdl.Rect{X: 2}) {
			x += 2
		}
		d = 1
	}
	this.Player2.SetDirect(d)
	this.Player2.SetXY(x, y)
}
